import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { queryCompany, queryCompanyDetail, addCompany, delCompany } from '@/services/company';

export interface CompanyModelState {
    data: any;
}

export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: CompanyModelState) => T) => T },
) => void;

export interface CompanyModelType {
    namespace: string;
    state: CompanyModelState;
    effects: {
        fetch: Effect;
        add: Effect;
        delete: Effect;
        // update: Effect;
    };
    reducers: {
        save: Reducer<CompanyModelState>;
    };
}

const Model: CompanyModelType = {
    namespace: 'company',

    state: {
        data: [],
    },

    effects: {
        *fetch(_, { call, put }) {
            const response = yield call(queryCompany);
            yield put({
                type: 'save',
                payload: response,
            });
        },
        *add({ payload, callback }, { call }) {
            yield call(addCompany, payload);
            if (callback) callback();
        },
        *delete({ payload, callback }, { call }) {
            yield call(delCompany, payload);
            if (callback) callback();
        },
        /* *update({ payload, callback }, { call, put }) {
          const response = yield call(updateRule, payload);
          yield put({
            type: 'save',
            payload: response,
          });
          if (callback) callback();
        }, */
    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                data: action.payload,
            };
        },
    },
};

export default Model;